const DIAM = 5;
const TEXT_OFFSET_X = 10;
const TEXT_OFFSET_Y = 10;
const max_cell = 16;



//OVERRIDE NAVSETACTIVE SAVING ACTIVE INDEX
//save base navSetActive in navSetActiveBase before overriding
tabberObj.prototype.navSetActiveBase = tabberObj.prototype.navSetActive;
tabberObj.prototype.navSetActive = function(tabberIndex) {
  //base method
  var baseReturn = this.navSetActiveBase(tabberIndex);
  
  tabberObj.activeIndex = tabberIndex;

  //base return
  return baseReturn;
};


$(document).ready(function() {
 
    buildSocket(floors);
    //show toolbar
    /*$("#nmptoolbar").nmptoolbar({toolbarButtons : [
          {image: 'images/new_floor.png', command: newFloorDialog, title: 'new floor'},
          {image: 'images/new_rack.png', command: newRackDialog, title: 'new rack'},
          {image: 'images/new_PP.png', command: newPatchPanelDialog, title: 'new patch panel'},  
          {image: 'images/new_socket.png', command: newSocketForm, title: 'new socket'},    
          {image: 'images/command5.png', command: function(){alert("command5");}, title: 'command5'},
          {image: 'images/command6.png', command: function(){alert("command6");}, title: 'command6'},
          {image: 'images/command7.png', command: function(){alert("command7");}, title: 'command7'},
          {image: 'images/command8.png', command: function(){alert("command8");}, title: 'command8'},
          {image: 'images/command9.png', command: function(){alert("command9");}, title: 'command9'},

    ]});*/
$("#newPatchPanelSubmit").click(newPatchPanelSubmit);

});


var buildSocket = function(floorsArray) {
    for (var i = 0; i <floorsArray.length; i++) {
        var paper = Raphael(document.getElementById('mappa'+i));
        var floorSockets = floorsArray[i];

        for (var j = 0; j < floorSockets.length; j++) {
            var wallSocket = floorSockets[j];

            var wsCircle = paper.circle(parseInt(wallSocket.coordX), parseInt(wallSocket.coordY), DIAM);
            wsCircle.attr("fill", "#f00");
            var wsText = paper.text(parseInt(wallSocket.coordX)+TEXT_OFFSET_X, 
                                    parseInt(wallSocket.coordY)+TEXT_OFFSET_Y, 
                                    wallSocket.floor+wallSocket.rack+
                                    wallSocket.patchPanel+wallSocket.socket);
            wsCircle.text = wsText;

            wsCircle.wallSocket = wallSocket;
            wallSocket.shape = wsCircle;
            wsCircle.drag(move, start, up);
        }
    }
};

var start = function () {
    // storing original coordinates
    this.ocx = this.attr("cx");
    this.ocy = this.attr("cy");
    this.text.ox = this.text.attr("x");
    this.text.oy = this.text.attr("y");
    
    this.attr({opacity: .5});
    this.text.attr({opacity: .5});
}, 
move = function (dx, dy) {
    // move will be called with dx and dy
    this.attr({cx: this.ocx + dx, cy: this.ocy + dy});
    this.text.attr({x: this.text.ox + dx, y: this.text.oy + dy});
},
up = function () {
    // restoring state
    this.attr({opacity: 1});
    this.text.attr({opacity: 1});
    this.wallSocket.coordX = this.attr("cx");
    this.wallSocket.coordY = this.attr("cy");
    updateSocket(this.wallSocket);
};

function updateSocket(wallSocket) {
     $.ajax({
         url: 'updateSocket.php',
         data: {id: wallSocket.id,
                coordX: wallSocket.coordX,
                coordY: wallSocket.coordY,
                used: '1'
            },
         type: 'get',
         dataType: 'json',
         success: function(jqXHR,p2){
             window.P1 = jqXHR;
             window.P2 = p2
         },
         error: function(jqXHR){
             window.P = jqXHR;
             alert(jqXHR.responseText);
         }
     })
     
};

function refreshRack(floor) {
     $.ajax({
        url: 'socketsForm.php',
        data: {level: 0, floor: floor},
        type: 'get',
        dataType: 'json',
        success: function(racks){
            for(i = 0; i<racks.length; i++){
                $('<option>'+racks[i]+'</option>').attr('value',racks[i]).appendTo($("#rackList"));
            }
            $("#floorList").attr('floor',floor);
        },
        error: function(jqXHR){
            alert(jqXHR.responseText);
        }
     })
};

function refreshPatchPanel(rack){

    var floor = $('#floorList').val()

    $.ajax({
        url: 'socketsForm.php',
        data: {level: 1, floor: floor, rack: rack},
        type: 'get',
        dataType: 'json',
        success: function (pp) {
            for(j=0; j<pp.length; j++) {
                $('<option>'+pp[j]+'</option>').attr('value',pp[j]).appendTo($("#ppList"));
            }
        },
        error: function(jqXHR) {
            window.P = jqXHR;
            alert(jqXHR.responseText);
        }
    })
};


function showSockets(patchPanel){
    var floor = $("#floorList").val()
    var rack = $("#rackList").val()
    
    $.ajax({
        url: 'socketsForm.php',
        data: {level: 2, floor: floor, rack: rack, patchPanel: patchPanel},
        type: 'get',
        dataType: 'json',
        success: function (sockets){
            var tbody = $("<tbody></tbody>");
            tbody.appendTo("#socketsTable");
            
            var trElement_current = null;
            for (var i = 0; i<sockets.length; i++) {
                
                var socket = sockets[i];    
                //used to set td background-color 
                var clr = [];
                clr[0] = "grey";
                clr[1] = "red";

                if (i % max_cell == 0) {
                    trElement_current = $("<tr></tr>");
                    trElement_current.appendTo(tbody);
                }

                //adding the cell to the current tr
                var tdElement = $('<td><span class="span">' + socket.socket + '</span></td>');
                tdElement.attr("id", "newsocket_" + socket.id);
                tdElement.attr("style","background-color:"+clr[socket.used]+";font-size:12px")
              
                console.debug(socket)
                tdElement.dblclick(socketFunction(socket))
                                       
                tdElement.appendTo(trElement_current)  
                }
        
            $("#socketsTable").appendTo($("#newSocketForm")) 
            // sets the border attribute of tbl to 1;
            $("#socketsTable").attr("border", "1");
        },
            error: function(jqXHR){
             window.P = jqXHR;
             alert(jqXHR.responseText);
            }
        
    }) 
};


function socketFunction(v) {
   
    return function(){

    if(v.used == 1) {

        $("#newsocket_"+v.id).attr("style","background-color:grey; font-size:12px");
        
        $.ajax({
            url: 'updateSocket.php',
            data: {
                id: v.id,
                coordX: v.coordX,
                coordY: v.coordY,
                used: 0 
            },
            type: 'get',
            dataType: 'json',
            success: function() {
                //alert("socket updated");
            },
            error: function(jqXHR,p2) {
                window.P = jqXHR;
                window.P2 = p2;
                alert(jqXHR.responseText);
            }
        });
    } else {

        $("#newsocket_"+v.id).attr("style","background-color:red;font-size:12px");
        $.ajax({
            url: 'updateSocket.php',
            data: {
                id: v.id,
                coordX: 50,
                coordY: 50,
                used: 1
            },
            type: 'get',
            dataType: 'json',
            success: function() {
                //alert("socket updated");
            },
            error: function(jqXHR,p2) {
                window.P = jqXHR;
                window.P2 = p2;
                alert(jqXHR.responseText);
            }
        });
    //    v.coordX = 50;
      //  v.coordY = 50;
        //once the cell has changed colour and data transferred to the DB show the sokcet on the map
      showSocketOnMap(v);
    
    }

    }
    self.switchto(v);
}

function showSocketOnMap(wallSocket){
            console.log(wallSocket)
           buildSocket(floors);
           
           var newPaper = Raphael(document.getElementById('mappa'+tabberObj.activeIndex));
            
            var wsCircle = newPaper.circle(parseInt(wallSocket.coordX), parseInt(wallSocket.coordY), DIAM);
            wsCircle.attr("fill", "#f00");
            var wsText = newPaper.text(parseInt(wallSocket.coordX)+TEXT_OFFSET_X, 
                                    parseInt(wallSocket.coordY)+TEXT_OFFSET_Y, 
                                    wallSocket.floor+wallSocket.rack+
                                    wallSocket.patchPanel+wallSocket.socket);
            wsCircle.text = wsText;

            wsCircle.wallSocket = wallSocket;
            wallSocket.shape = wsCircle;
            wsCircle.drag(move, start, up);
}
 
 